--[[
返回值:
1 抢购成功
2 抢购活动不存在
4 重复下单
8 库存不足
]]--
local k_seckill = KEYS[1]
local k_queuing = KEYS[2]
local v_count = tonumber(ARGV[1])

local seckill = redis.call("hmget", k_seckill, "total", "booked")
-- 判断活动是否存在
if (not (seckill[1] or seckill[2])) then
    return 2
end

local total = tonumber(seckill[1] or 0)
local booked = tonumber(seckill[2] or 0)
-- 判断库存是否充足
if (total - booked < v_count) then
    return 8
end
-- TODO 判断时效

-- 减库存
redis.call("hincrby", k_seckill, "booked", v_count)
redis.call("setex", k_queuing, 300, "0|") -- 队列状态
return 1
